<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Ttc\Controller;
use Ttc\Controller\PublicController;

/**
 * 土特产用户
 */
class UserController extends PublicController {

    /* 身份证验证 */
    public function AutIDcard(){
        $data = inputJson();

        //假数据
        // $data['phpsid'] = 'bqodcvt6gbl9k700ql2afqifr4';
        // $data['is_check'] = 1;
        // $data['identity_card'] = '441881199234556672';
        // $data['real_name'] = '薛鹏';
        // $data['card_face'] = '11111';
        // $data['card_back'] = '11111';

        //判断有没有登录
        $state = is_login($data['phpsid']);
        if($state == 0){
            abnormalOutputJson(['info'=>'请先登录','type'=>1]);
        }
        if(empty($data['real_name'])){
            abnormalOutputJson(['info'=>'请输入真实姓名','type'=>2]);
        }
        if(empty($data['identity_card'])){
            abnormalOutputJson(['info'=>'请输入身份证号','type'=>3]);
        }
        if(empty($data['card_face'])){
            abnormalOutputJson(['info'=>'请上传身份证正面照','type'=>4]);
        }
         if(empty($data['card_back'])){
            abnormalOutputJson(['info'=>'请上传身份证背面照','type'=>5]);
        }
        //有没有同意协议
        if($data['is_check'] != 1){
            abnormalOutputJson(['info'=>'请先同意将身份证信息交由平台进行身份验证','type'=>6]);
        }

        //查用户id
        $member_id =get_userId($data['phpsid']);
        
        //第三方认证
        $result = point_json_post_http_curl([
            'user_id' => $member_id,
            'cardno' => $data['identity_card'],
            'name' => $data['real_name'],
            'face_card' => $data['card_face'],
            'back_card' => $data['card_back']
        ]);

        //假数据
        // $result = array(
        //         'status'=>"ok",
        //         'msg'=>"",
        //         'data'=>array(
        //                 'info'=>"身份认证成功",
        //             )
        //     );        

        //改变实名认证状态
        $api_ret = $result;
        //认证成功
        if($api_ret['status'] == 'ok'){
            $state = 1;
            $TtcMember = D('TtcMember');
            $res = $TtcMember->saveIdenState(array('id'=>$member_id),$state);
            if($res === false){
                errorOutputJson('d'.__LINE__);
            }else{
                successOutputJson();
            }
        }else{
            //认证失败
            $state = 0;
            $TtcMember = D('TtcMember');
            $res = $TtcMember->saveIdenState(array('id'=>$member_id),$state);
            if($res === false){
                errorOutputJson('d'.__LINE__);
            }else{
                abnormalOutputJson(['info'=>'认证失败','type'=>7]);
            }
        }
    }

    /**
     * 默认联系人
     */
    public function DefaultContact(){
        $data = inputJson();

        // $data['phpsid']='bqodcvt6gbl9k700ql2afqifr4';

        //判断有没有登录
        $state = is_login($data['phpsid']);
        if($state == 0){
            abnormalOutputJson(['info'=>'请先登录']);
        }

        //用户id
        $member_id =get_userId($data['phpsid']);
        
        $condition = array(
            'member_id'=>$member_id,
            'is_default'=>1,
            'state'=>['GT',0]
            );
        $field = 'id,contact_name,contact_phone,contact_wechat,areaid_1,areaid_2,areaid_3,detailed_address';

        $Contact = D('Contact');
        $res = $Contact->getOneContact($condition,$field);
        if($res === false){
            errorOutputJson('d'.__LINE__);
        }elseif(empty($res)){
            successOutputJson();
        }else{            
            $rdata['id'] = $res['id'];
            $rdata['contact_name'] = $res['contact_name'];
            $rdata['contact_phone'] = $res['contact_phone'];
            $rdata['contact_wechat'] = $res['contact_wechat'];
            $rdata['prov'] = $res['areaid_1'];
            $rdata['city'] = $res['areaid_2'];
            $rdata['area'] = $res['areaid_3'];
            $rdata['detailed_address'] = $res['detailed_address'];
            successOutputJson($rdata);
        }

    }

    /**
     * 联系人列表
     */
    public function ContactLists(){
        $data = inputJson();

        // $data['phpsid']='bqodcvt6gbl9k700ql2afqifr4';
        $data['rows']=10;
        // $data['page']=1;

        //判断有没有登录
        $state = is_login($data['phpsid']);
        if($state == 0){
            abnormalOutputJson(['info'=>'请先登录']);
        }

        $member_id =get_userId($data['phpsid']);

        
        $Contact = D('Contact');
        $condition = array('member_id'=>$member_id,'state'=>['GT',0]); //状态非删除状态
        $field = 'id,contact_name,contact_phone,contact_wechat,areaid_1,areaid_2,areaid_3,detailed_address,is_default';
        //总条数
        $num = $Contact->getNum($condition);
        //列表
        $res = $Contact->getAllContactPage($condition,$field,'is_default desc,up_time desc,id desc',$data['page'],$data['rows']);

        // var_dump($res);

        if($res === false){
            errorOutputJson('d'.__LINE__);
        }elseif(empty($res)){
            successOutputJson();
        }else{
            // var_dump($res);
            foreach ($res as $k => $v) {
                $rdata[$k]['id'] = $v['id'];
                $rdata[$k]['is_default'] = $v['is_default'];
                $rdata[$k]['contact_name'] = $v['contact_name'];
                $rdata[$k]['contact_phone'] = $v['contact_phone'];
                $rdata[$k]['contact_wechat'] = $v['contact_wechat'];
                $rdata[$k]['prov'] = $v['areaid_1'];
                $rdata[$k]['city'] = $v['areaid_2'];
                $rdata[$k]['area'] = $v['areaid_3'];
                $rdata[$k]['detailed_address'] = $v['detailed_address'];
            }
            // var_dump($rdata);
            successOutputJson($rdata,['total'=>$num]);
        }
        
    }

    /**
     * 保存/修改联系人
     */
    public function UpdateContact(){

        $data = inputJson();

        //假数据
        // $data['phpsid']='veu8ds0l22dl6868kj140kspu2';
        // $data['contact_name']='444';
        // $data['contact_phone']='122222222222';
        // $data['contact_wechat']='1111111111';
        // $data['areaid_1']='2222222222';
        // $data['areaid_2']='444';
        // $data['areaid_3']='222';
        // $data['longitude']='222';
        // $data['latitude']='22';
        // $data['detailed_address']='31';
        // $data['contact_id']= 31;
        // $data['token']= 31;

        //检查令牌
        $token = $this->validataToken($data['token']);//成功返回新的令牌 接口调用末尾返回给前端
        if($token == -2){
            errorOutputJson('d'.__LINE__);//没有初始化令牌
        }elseif ($token == -3) {
            errorOutputJson('d'.__LINE__);//存储新令牌出错
        }elseif ($token == -1) {
            abnormalOutputJson(['info'=>'请求太快','type'=>4]);
        }

        //判断有没有登录
        $state = is_login($data['phpsid']);
        if($state == 0){
            abnormalOutputJson(['info'=>'请先登录','type'=>1]);
        }
        //查用户id
        $member_id =get_userId($data['phpsid']);
        
        $rdata['member_id']=$member_id;
        $rdata['contact_name']=$data['contact_name'];
        $rdata['contact_phone']=$data['contact_phone'];
        $rdata['contact_wechat']=$data['contact_wechat'];
        $rdata['areaid_1']=$data['areaid_1'];
        $rdata['areaid_2']=$data['areaid_2'];
        $rdata['areaid_3']=$data['areaid_3'];
        $rdata['state']=1;
        $rdata['longitude']=$data['longitude'];
        $rdata['latitude']=$data['latitude'];
        $rdata['detailed_address']=$data['detailed_address'];

        // var_dump($rdata);
        //判断是增加还是修改 有值-修改 空-增加
        if(!empty($data['contact_id'])){
            $rdata['up_time']=time();
            $Contact = D('Contact');
            $condition = array('id'=>$data['contact_id']);
            $res = $Contact->saveContact($condition,$rdata);
            //字段验证出错
            if($res === false){
                errorOutputJson('d'.__LINE__);
            }elseif(isset($res['msg'])){
                abnormalOutputJson(['info'=>$res['info'],'type'=>2]);
            }else{
                successOutputJson();
            }
        }else{
            $rdata['add_time']=$rdata['up_time']=time();
            $Contact = D('Contact');
            //查询地址有没有满20条，满了则不允许再添加
            $ccounts = $Contact->getNum(array('member_id'=>$member_id,'state'=>['GT',0]));
            if($ccounts >= 20){
                abnormalOutputJson(['info'=>'地址已经满20条，不能再添加','type'=>3]);
            }

            //如果新增的是用户的第一个地址，就设置为默认地址，否则非默认
            $cres = $Contact->getOneContact(array('member_id'=>$member_id,'state'=>['GT',0]));
            // var_dump($cres);
            //是第一个地址 把地址名称作为店铺名称存入用户表
            if(empty($cres)){
                $rdata['is_default']= 1;
                $res = $Contact->addContact($rdata);
                if($res === false){
                    errorOutputJson('d'.__LINE__);
                }elseif(isset($res['msg'])){
                    abnormalOutputJson(['info'=>$res['info'],'type'=>2]);
                }

                $mdata['id'] = $member_id;
                $mdata['store_name'] = $rdata['contact_name'];
                $ff = D('TtcMember')->save($mdata);

                if($ff === false){
                    errorOutputJson('d'.__LINE__);
                }else{
                    successOutputJson($res,['token'=>$token]);
                }

            }else{
                $rdata['is_default']= 0;
                $res = $Contact->addContact($rdata);

                //字段验证出错
                if($res === false){
                    errorOutputJson('d'.__LINE__);
                }elseif(isset($res['msg'])){
                    abnormalOutputJson(['info'=>$res['info'],'type'=>2]);
                }else{
                    successOutputJson($res,['token'=>$token]);
                }
            }

            
        }

    }

     /**
     * 删除联系人
     */
    public function DeleteContact(){
        $data = inputJson();

        // $data['phpsid']='bqodcvt6gbl9k700ql2afqifr4';
        // $data['contact_id']=21;

        //判断有没有登录
        $state = is_login($data['phpsid']);
        if($state == 0){
            abnormalOutputJson(['info'=>'请先登录']);
        }
        //用户id
        $member_id =get_userId($data['phpsid']);

        $Contact = D('Contact');
        //是否删了默认地址，如果是，则选中下一个为默认地址
        $res = $Contact->find($data['contact_id']);
        //现有多少条地址,如果删的是最后一个地址则不用设置下一个为默认
        $count =$Contact->getNum(array('member_id'=>$member_id,'state'=>['GT',0]));
        if($res['is_default'] == 1 && $count >1){
            //删除地址 改 状态为0
            $adata['id'] = $data['contact_id'];
            $adata['state'] = 0;
            $adata['is_default'] = 0;

            $dres = $Contact->save($adata);
            if($dres !== false){
                //选中下一个为默认地址
                $cid = $Contact->getOneContact(array('member_id'=>$member_id,'state'=>['GT',0]),'id');
                $addata['id'] = $cid['id'];
                $addata['is_default'] = 1;
                $res=$Contact->save($addata);
                if($res === false){
                    errorOutputJson('d'.__LINE__);            
                }else{
                    successOutputJson();
                }
            }else{
                errorOutputJson('d'.__LINE__);            
            }
        }else{
            //删除地址 改 状态为0
            $adata['id'] = $data['contact_id'];
            $adata['state'] = 0;
            $dres = $Contact->save($adata);
            if($dres !== false){
                successOutputJson();
            }else{
                errorOutputJson('d'.__LINE__);            
            }
        }

    }

    /**
     * 设置默认联系人
     */
    public function setDefaultContact(){
        $data = inputJson();

        // $data['phpsid']='jm8q10t5pht4omise21fk2gqv3';
        // $data['contact_id']=20;

        //判断有没有登录
        $state = is_login($data['phpsid']);
        if($state == 0){
            abnormalOutputJson(['info'=>'请先登录']);
        }

        $member_id =get_userId($data['phpsid']);
        $Contact = D('Contact');
        //先将全部设置为o
        $condition = array('member_id'=>$member_id);
        $da['is_default'] = 0;
        $res = $Contact->saveDefalut($condition,$da);
        if($res === false){
            errorOutputJson('d'.__LINE__);            
        }else{
            //将选中设置为1（默认）
            $condition = array('id'=>$data['contact_id'],'member_id'=>$member_id);
            $da['is_default'] = 1;
            $res = $Contact->saveDefalut($condition,$da);

            if($res === false){
                errorOutputJson('d'.__LINE__);            
            }else{
                successOutputJson();
            }
        }
        
    }

}
